package com.simon.hse.activity.education;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.google.gson.Gson;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.simon.hse.R;
import com.simon.hse.activity.BaseActivity;
import com.simon.hse.adapter.CommonEmptyAdapter;
import com.simon.hse.adapter.CommonViewHolder;
import com.simon.hse.http.CommonCallBack;
import com.simon.hse.http.HttpManager;
import com.simon.hse.http.entity.ExaminManageInput;
import com.simon.hse.http.entity.ExaminManageOutput;
import com.simon.hse.utils.ToastUtils;

import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;

import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;

/**
 * 考试管理
 */
@SuppressWarnings("all")
@ContentView(R.layout.activity_examination_manager)
public class ExaminationManagerActivity extends BaseActivity {
    @ViewInject(R.id.tv_common_title)
    TextView mTv_common_title;

    @ViewInject(R.id.et_examin_manage_course)
    EditText mEt_examin_manage_course;

    @ViewInject(R.id.smartrefresh)
    SmartRefreshLayout mSmartRefresh;

    @ViewInject(R.id.recyclerview)
    RecyclerView mRecyclerView;


    private int currentPage = 1, totalPage = 1;
    private CommonEmptyAdapter mCommonEmptyAdapter;
    private List<ExaminManageOutput.DataBean.PageDataBean> mDataBeanList = new ArrayList<>();// 考试列表

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mTv_common_title.setText("考试管理");

        initRecyclerView();
        initData();
    }

    @Event(value = {R.id.iv_common_left})
    private void back(View view) {
        Intent intent = new Intent();
        switch (view.getId()) {
            case R.id.iv_common_left:
                finish();
                break;
        }
    }

    private void initRecyclerView() {
        mEt_examin_manage_course.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                initData();
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });

        mSmartRefresh.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                if (currentPage*10 < totalPage) {
                    currentPage++;
                    initData();
                } else {
                    mSmartRefresh.finishLoadMoreWithNoMoreData();
                }
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                currentPage = 1;
                mDataBeanList.clear();
                initData();
            }
        });

        LinearLayoutManager llm = new LinearLayoutManager(ExaminationManagerActivity.this);
        mRecyclerView.setLayoutManager(llm);
        // 如果Item够简单，高度是确定的，打开FixSize将提高性能
        mRecyclerView.setHasFixedSize(true);
        // 设置Item默认动画，加也行，不加也行
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mRecyclerView.setNestedScrollingEnabled(false);

        mCommonEmptyAdapter = new CommonEmptyAdapter(ExaminationManagerActivity.this, R.layout.layout_item_examin_manager, mDataBeanList);
        mCommonEmptyAdapter.setItemDataListener(new CommonEmptyAdapter.ItemDataListener<ExaminManageOutput.DataBean.PageDataBean>() {
            @Override
            public void setItemData(CommonViewHolder holder, final ExaminManageOutput.DataBean.PageDataBean dataBean) {
                TextView tv_examin_manage_title = holder.getView(R.id.tv_examin_manage_title);
                TextView tv_examin_manage_score = holder.getView(R.id.tv_examin_manage_score);
                TextView tv_examin_manage_pass = holder.getView(R.id.tv_examin_manage_pass);
                TextView tv_examin_manage_state = holder.getView(R.id.tv_examin_manage_state);
                TextView tv_examin_manage_date = holder.getView(R.id.tv_examin_manage_date);

                holder.getView(R.id.tv_examin_again).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Intent intent = new Intent();
                        Bundle bundle = new Bundle();
                        intent.setClass(ExaminationManagerActivity.this, OnlineExaminationActivity.class);
                        bundle.putString("TITLE", "在线考试");
                        bundle.putString("TYPE", "1");
                        bundle.putString("ID", dataBean.getId());
                        intent.putExtras(bundle);
                        startActivity(intent);
                    }
                });
                holder.getView(R.id.tv_examin_simulate).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Intent intent = new Intent();
                        Bundle bundle = new Bundle();
                        intent.setClass(ExaminationManagerActivity.this, OnlineExaminationActivity.class);
                        bundle.putString("TITLE", "模拟考试");
                        bundle.putString("ID", dataBean.getId());
                        intent.putExtras(bundle);
                        startActivity(intent);
                    }
                });
                holder.getView(R.id.tv_examin_detail).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Intent intent = new Intent();
                        Bundle bundle = new Bundle();
                        intent.setClass(ExaminationManagerActivity.this, ExaminationDetailActivity.class);
                        bundle.putString("ID", dataBean.getId());
                        intent.putExtras(bundle);
                        startActivity(intent);
                    }
                });

                tv_examin_manage_title.setText(dataBean.getNameoftrainingplan());
                int qualificationscore = dataBean.getQualificationscore();
                int examinationscore = dataBean.getExaminationscore();
                int status = dataBean.getStatus();
                if (status == 0) {
                    // tv_examin_manage_state.setText("未作答");
                    // tv_examin_manage_score.setText("未开始");
                    // tv_examin_manage_score.setBackgroundResource(R.drawable.rect_dark_gray_corner_bottom_5);
                } else {
                    // tv_examin_manage_state.setText("已作答");
                    tv_examin_manage_score.setText(examinationscore + "分");
                    if (examinationscore < qualificationscore) {
                        tv_examin_manage_score.setBackgroundResource(R.drawable.rect_red_corner_bottom_5);
                    } else {
                        tv_examin_manage_score.setBackgroundResource(R.drawable.rect_green_corner_bottom_5);
                    }
                }
                tv_examin_manage_pass.setText(qualificationscore + "分及格线");
                tv_examin_manage_state.setText(dataBean.getStatusText());

                // 考试时间
                String starttime = dataBean.getExaminationstarttime();
                String endtime = dataBean.getEndtimeofexamination();
                String[] splitStart = starttime.split(" ");
                String[] splitEnd = endtime.split(" ");
                String[] splitStartHour = splitStart[1].split(":");
                String[] splitEndHour = splitEnd[1].split(":");
                tv_examin_manage_date.setText(splitStart[0] + " " + splitStartHour[0] + ":" + splitStartHour[1] + "-" + splitEndHour[0] + ":" + splitEndHour[1]);
            }
        });

        mCommonEmptyAdapter.setOnItemEmptyClickListener(new CommonEmptyAdapter.OnItemEmptyClickListener() {
            @Override
            public void setOnEmptyClickListener() {
                initData();
            }

            @Override
            public void setOnItemClickListener(View view, int position) {

            }

            @Override
            public void setOnItemLongClickListener(View view, int position) {

            }
        });

        mCommonEmptyAdapter.setHasStableIds(true);
        mRecyclerView.setAdapter(mCommonEmptyAdapter);
    }

    private void initData() {
        ExaminManageInput examinManageInput = new ExaminManageInput();
        ExaminManageInput.ModelBean modelBean = new ExaminManageInput.ModelBean();
        String course = mEt_examin_manage_course.getText().toString();
        if (!TextUtils.isEmpty(course)) {
            ExaminManageInput.ModelBean.PXPlanBean planBean = new ExaminManageInput.ModelBean.PXPlanBean();
            planBean.setNameoftrainingplan(course);
            modelBean.setPX_Plan(planBean);
        }
        examinManageInput.setModel(modelBean);
        examinManageInput.setLimit(10);
        examinManageInput.setOffset(10 * (currentPage - 1));

        Call<String> call = HttpManager.getInstance().requestService().EXAMIN_MANAGE_LIST(HttpManager.getInstance().requestBody(examinManageInput));
        HttpManager.getInstance().requestCallBack(call, new CommonCallBack<String>() {
            @Override
            public void requestSuccess(String result) {
                ExaminManageOutput examinManageOutput = new Gson().fromJson(result, ExaminManageOutput.class);
                if (examinManageOutput.getResult().equals("Success")) {
                    totalPage = examinManageOutput.getData().getRowCount();
                    List<ExaminManageOutput.DataBean.PageDataBean> dataBeanList = examinManageOutput.getData().getPageData();
                    mDataBeanList.addAll(dataBeanList);
                    mCommonEmptyAdapter.notifyDataSetChanged();

                    mSmartRefresh.finishRefresh();
                    mSmartRefresh.finishLoadMore();
                } else {
                    ToastUtils.getInstance().showShortToastBottom(examinManageOutput.getMessage());
                }
            }

            @Override
            public void requestError(String errorMsg) {
                ToastUtils.getInstance().showShortToastBottom(errorMsg);
            }
        });
    }

}
